package com.geekstudy.week11;

import redis.clients.jedis.Jedis;

public class RedisStockService {

    static final String STOCK = "stock";

    Jedis jedis;

    public RedisStockService (Jedis jedis) {
        this.jedis = jedis;
    }

    /**
     *
     * 重置库存
     *
     * @param product 商品
     * @param stock 存库
     * @return 返回库存数量
     */
    public long resetStock(String product, long stock) {
        long value = 0;
        Long result = jedis.hset(STOCK, product, String.valueOf(stock));
        if(result != null) {
            value = Long.valueOf(jedis.hget(STOCK, product)).longValue();
        }
        return value;
    }

    /**
     *
     * 增加库存
     *
     * @param product 商品
     * @param stock 库存
     * @return 增加库存后的库存数量
     */
    public long addStock(String product, long stock) {
        long value = 0;
        Long result = jedis.hincrBy(STOCK, product, stock);
        if(result != null) {
            value = result.longValue();
        }
        return value;
    }

    /**
     *
     * 扣减库存
     *
     * @param product 商品
     * @param stock 库存
     * @return 扣减库存后的库存数量
     */
    public long subtractStock(String product, long stock) {
        long value = 0;
        Long result = jedis.hincrBy(STOCK, product, stock * -1);
        if(result != null) {
            value = result.longValue();
        }
        return value;
    }
}
